﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MT.Common;
using MT.Common.Helper;
using MT.Common.Helpers;
using MT.Models.Entity;
using MT.WebApi.Core.Auth.OverWrite;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace MT.WebApi.Core.ConfigureServices
{
    public static class StartupConfigure
    {

        public static void Build(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IHttpContextAccessor accessor)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }



            app.UpdateDatabase();

            MvcContext.Accessor = accessor;

            // app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            app.UseCors("AllowAnyOrigin");
            loggerFactory.AddNLog();
            env.ConfigureNLog(Path.Combine("Config", "Nlog.config"));
            app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseMiddleware<JwtTokenAuth>();

            app.UseMiniProfiler();
            app.UseMvc();

            //配置支持nginx
            //app.UseForwardedHeaders(new ForwardedHeadersOptions {
            //    ForwardedHeaders=Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor|Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto
            //});
            app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MT.Api");
            });
        }
        private static void UpdateDatabase(this IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {

                using (var db = scope.ServiceProvider.GetService<AppDbContext>())
                {
                    db.Database.Migrate();
                    if (db.User == null)
                    {
                        int passwordSalt = PasswordHelper.CreatePasswordSalt();
                        string password = ConfigHelper.GetSection("DefaultLoginPwd");
                        string PasswordHash = new string(PasswordHelper.CreatePasswordHash(password, passwordSalt));
                        db.User.Add(new User()
                        {
                            Active = true,
                            Birthday = null,
                            CardId = "",
                            CardTypeDic = "",
                            ClientTypeDic = "",
                            CreateTime = DateTime.Now,
                            Delete = false,
                            DingDepartments = "",
                            DingDingUnionid = "",
                            DingDingUserId = "",
                            Email = "",
                            ExpireTime = DateTime.MaxValue,
                            ExpireTypeDic = "perm",
                            Name = "超级管理员",
                            NationDic = "ha",
                            Note = "",
                            PasswordHash = PasswordHash,
                            PasswordSalt = passwordSalt,
                            PhoneNumber = "13111111111",
                            SexDic = "unkown",
                            UpdateTime = DateTime.Now,
                            UserName = "admin"
                        });
                        db.SaveChanges();
                    }
                }
            }
        }
    }
}
